package org.dromara.components.http;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpRequestUtil {
    private static String contentTypeJson = "application/json";

    public static String get(String url,Object reqParam){
        if(ObjectUtil.isNotEmpty(reqParam)){
            String jsonQueryStr = JSONUtil.toJsonStr(reqParam);
            Map<String,Object> getParam = JSONUtil.toBean(jsonQueryStr, HashMap.class);
            StringBuffer paramBuffer = new StringBuffer();
            for (Map.Entry<String,Object> entry:getParam.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if(paramBuffer.length() > 0){
                    paramBuffer.append("&");
                }
                paramBuffer.append(key).append("=").append(value.toString());
            }
            if(paramBuffer.length() > 0){
                url = url + "?" + paramBuffer.toString();
            }
        }
        log.info("get请求url：{}",url);
        String respStr = HttpRequest.get(url).execute().body();
        log.info("响应结果：{}", respStr);
        return respStr;
    }
    public static String jsonPost(String url,Object reqParam){
        String jsonQueryStr = JSONUtil.toJsonStr(reqParam);
        log.info("请求url：{}，post.json请求参数：{}",url,jsonQueryStr);
        String respStr = HttpRequest.post(url).contentType(contentTypeJson).body(jsonQueryStr).execute().body();
        log.info("响应结果：{}", respStr);
        return respStr;
    }

    public static String formPost(String url,Object reqParam){
        String jsonQueryStr = JSONUtil.toJsonStr(reqParam);
        Map<String,Object> formParam = JSONUtil.toBean(jsonQueryStr, HashMap.class);
        log.info("请求url：{}，post.form请求参数：{}",url,formParam);
        String respStr = HttpRequest.post(url).form(formParam).execute().body();
        log.info("响应结果：{}", respStr);
        return respStr;
    }
}
